package com.wyzz.hr.action;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.wyzz.hr.base.BaseAction;
import com.wyzz.hr.bo.IClientBO;
import com.wyzz.hr.bo.IEmailsendBO;
import com.wyzz.hr.bo.IEmailtemplateBO;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.UserBo;
import com.wyzz.hr.pojo.Emailsend;
import com.wyzz.hr.pojo.Emailtemplate;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Userinfo;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.StringUtil;

public class UserCreateAction extends BaseAction {

	public UserCreateAction() {
		msgUserRelate = "\u7528\u6237\u6240\u5173\u8054\u7684\u89D2\u8272\u8FC7\u591A\uFF01";
		msgUsernnameExist = "\u7528\u6237\u540D{0}\u5DF2\u7ECF\u5B58\u5728\uFF01";
	}

	public String execute() throws Exception {
		String array[] = empIds.split(";");
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Employee.class);
		detachedCriteria.add(Restrictions.in(Employee.PROP_ID, array));
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		List list = empBo.findByCriteria(detachedCriteria);
		int number = array.length;
		int unSuccessNumber = 0;
		String roleIdString[] = roleIds.split(",");
		if (roleIdString.length > 45) {
			addActionError(StringUtil.message(msgUserRelate, new Object[0]));
			return "input";
		}
		roleId = new Integer[roleIdString.length];
		for (int i = 0; i < roleIdString.length; i++)
			roleId[i] = Integer.valueOf(roleIdString[i]);

		IClientBO clientLimit = (IClientBO) SpringBeanFactory
				.getBean("clientBo");
		String limitInfo = clientLimit.checkUserLimit(roleId, number);
		if (!"success".equals(limitInfo))
			return limitInfo;
		UserBo userService = (UserBo) SpringBeanFactory.getBean("userService");
		if (StringUtils.isNotEmpty(user.getUiUsername())
				&& userService.getUserByName(user.getUiUsername()) != null) {
			addFieldError("user.uiUsername", StringUtil.message(
					msgUsernnameExist, new Object[] { user.getUiUsername() }));
			return "input";
		}
		List mailsendList = new ArrayList();
		IEmailtemplateBO templateBo = (IEmailtemplateBO) SpringBeanFactory
				.getBean("emailtemplateBO");
		Emailtemplate template = templateBo.getEmailTemplateByNo("NewUser");
		HttpSession session = ServletActionContext.getRequest().getSession();
		Employee currentEmployee = ((Userinfo) session.getAttribute("userinfo"))
				.getEmployee();
		IEmailsendBO emailsendBo = (IEmailsendBO) SpringBeanFactory
				.getBean("emailsendBO");
		for (int j = 0; j < number; j++) {
			Employee emp = (Employee) list.get(j);
			Userinfo tempUser = new Userinfo();
			tempUser.setId(emp.getId());
			if (StringUtils.isEmpty(user.getUiUsername()))
				tempUser.setUiUsername(emp.getEmpDistinctNo());
			else
				tempUser.setUiUsername(user.getUiUsername().trim());
			String password = user.getUiPassword();
			if (StringUtils.isEmpty(password))
				password = RandomStringUtils.random(6, true, true);
			tempUser.setUiPasswordEncrypt(StringUtil.encodePassword(password));
			tempUser.setUiStatus(Integer.valueOf(1));
			tempUser.setUiLevelRestrict(user.getUiLevelRestrict());
			tempUser.setUiMacRestrict(user.getUiMacRestrict());
			tempUser.setEmployee(emp);
			if (!userService.addUser(tempUser, roleId, currentEmployee.getId())) {
				unSuccessNumber++;
			} else {
				Employee receiver = empBo.loadEmp(tempUser.getId(), null);
				Map paramUserEmail = new HashMap();
				paramUserEmail.put("SENDER", currentEmployee);
				paramUserEmail.put("APPLIER", receiver);
				paramUserEmail.put("USERNAME", tempUser.getUiUsername());
				paramUserEmail.put("PASSWORD", password);
				paramUserEmail.put("URL", "configuration/login.jsp");
				Emailsend send = emailsendBo.getEmailUser(paramUserEmail,
						template);
				mailsendList.add(send);
			}
		}

		emailsendBo.sendEmailsMain(mailsendList);
		addSuccessInfo((new StringBuilder()).append("\u6DFB\u52A0").append(
				number).append("\u4E2A\u7528\u6237\u3002").toString());
		if (unSuccessNumber > 0)
			addErrorInfo((new StringBuilder()).append("\u6DFB\u52A0").append(
					unSuccessNumber).append(
					"\u4E2A\u7528\u6237\u5931\u8D25\uFF01").toString());
		return "success";
	}

	public Integer[] getRoleId() {
		return roleId;
	}

	public void setRoleId(Integer roleId[]) {
		this.roleId = roleId;
	}

	public Userinfo getUser() {
		return user;
	}

	public void setUser(Userinfo user) {
		this.user = user;
	}

	public String getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(String roleIds) {
		this.roleIds = roleIds;
	}

	public String getUiPassword() {
		return uiPassword;
	}

	public void setUiPassword(String uiPassword) {
		this.uiPassword = uiPassword;
	}

	public String getEmpIds() {
		return empIds;
	}

	public void setEmpIds(String empIds) {
		this.empIds = empIds;
	}

	public String getEmpNames() {
		return empNames;
	}

	public void setEmpNames(String empNames) {
		this.empNames = empNames;
	}

	String msgUserRelate;
	String msgUsernnameExist;
	private static final long serialVersionUID = 1L;
	private Userinfo user;
	private String empIds;
	private String empNames;
	private String uiPassword;
	private String roleIds;
	private Integer roleId[];
}
